package com.site.springboot.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.esp.commentdemo.entity.NewsComment;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.site.springboot.core.dao.NewsMapper;
import com.site.springboot.core.entity.News;
import com.site.springboot.core.entity.NewsComVO;
import com.site.springboot.core.entity.NewsExcelVO;
import com.site.springboot.core.service.CommentFeginService;
import com.site.springboot.core.service.NewsService;
import com.site.springboot.core.util.PageQueryUtil;
import com.site.springboot.core.util.PageResult;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

@Service
public class NewsServiceImpl implements NewsService {
    private final Logger logger = Logger.getLogger(NewsServiceImpl.class.getName());

    @Resource
    private NewsMapper newsMapper;

    @Resource
    private CommentFeginService commentFeginService;



    @Override
    public String saveNews(News news) {
        news.setCreateTime(new Date());
        news.setNewsViews(0L);
        news.setIsDeleted((byte) 0);
//        if (newsMapper.insertSelective(news) > 0) {
        if (newsMapper.insert(news) > 0) {
            return "success";
        }
        return "保存失败";
    }
    @Override
    public News queryNewsById(Long newsId) {
        System.out.println("我从缓存中拿数据");
        logger.info("getNews by %d in redisdb".formatted(newsId));
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("news_id", newsId)
                .eq("is_deleted", 0);
//        return newsMapper.selectByPrimaryKey(newsId);
        return newsMapper.selectOne(queryWrapper);
    }

    @Override
    public Boolean deleteBatch(Integer[] ids) {
        List<Integer> listId = Arrays.asList(ids);
//        return newsMapper.deleteBatch(ids)>0;
        return newsMapper.deleteBatchIds(listId)>0;
    }
    @Override
    public String updateNews(News news) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("news_id", news.getNewsId())
                .eq("is_deleted", 0);
//        News newsForUpdate = newsMapper.selectByPrimaryKey(news.getNewsId());
        News newsForUpdate = newsMapper.selectOne(queryWrapper);
        if (newsForUpdate == null) {
            return "数据不存在";
        }
        news.setNewsCategoryId(news.getNewsCategoryId());
        news.setNewsContent(news.getNewsContent());
        news.setNewsCoverImage(news.getNewsCoverImage());
        news.setNewsStatus(news.getNewsStatus());
        news.setNewsTitle(news.getNewsTitle());
        news.setUpdateTime(new Date());

        UpdateWrapper<News> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(news.getNewsTitle()!=null,"news_title",news.getNewsTitle())
                .set(news.getNewsContent()!=null,"news_content",news.getNewsContent())
                .set(news.getNewsCoverImage()!=null,"news_cover_image",news.getNewsCoverImage())
                .set(news.getNewsStatus()!=null,"news_status",news.getNewsStatus())
                .set(news.getIsDeleted()!=null,"is_deleted",news.getIsDeleted())
                .set(news.getUpdateTime()!=null,"update_time",news.getUpdateTime())
                .set(news.getCreateTime()!=null,"create_time",news.getCreateTime())
                .set(news.getNewsViews()!=null,"news_views",news.getNewsViews())
                .set(news.getNewsCategoryId()!=null,"news_category_id",news.getNewsCategoryId())
                .and(id->id.eq("news_id", news.getNewsId()));

//        if (newsMapper.updateByPrimaryKeySelective(news) > 0) {
        if (newsMapper.update(news,updateWrapper) > 0) {
            return "success";
        }
        return "修改失败";
    }

    @Override
    public PageResult getNewsPage(PageQueryUtil pageUtil) {
        int page = pageUtil.getPage();
        int limit = pageUtil.getLimit();

        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0)
                .orderByDesc("news_id");

        Page<News> newsPage = new Page<>(page, limit);
        Page<News> news = newsMapper.selectPage(newsPage, queryWrapper);

        int total = Math.toIntExact(newsMapper.selectCount(queryWrapper));
        PageResult pageResult = new PageResult(news.getRecords(), total, limit, page);
//        List<News> newsList = newsMapper.findNewsList(pageUtil);
//        int total = newsMapper.getTotalNews(pageUtil);
//        PageResult pageResult = new PageResult(newsList, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }

    @Override
    public PageResult getNewsAndCommnetOrder(PageQueryUtil pageUtil) {
        int limit = pageUtil.getLimit();
        int page = pageUtil.getPage();

        IPage<NewsComVO> IPage = newsMapper.selectJoinPage(new Page<>(page, limit), NewsComVO.class,
                new MPJLambdaWrapper<News>()
                        .selectAll(News.class)
                        .select(NewsComment::getNewsId,NewsComment::getCommentBody)
                        .leftJoin(NewsComment.class, NewsComment::getNewsId, News::getNewsId)
                        .orderByDesc(News::getCreateTime)
        );
        List<NewsComVO> records = IPage.getRecords();
        PageResult pageResult = new PageResult(records, (int) IPage.getTotal(), limit, page);


//        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("is_deleted", 0)
//                .orderByDesc("update_time");
//        List<News> newsList = newsMapper.selectList(queryWrapper);
//        for (int i = 0;i<newsList.size();i++) {
//            News news = newsList.get(i);
//            QueryWrapper<NewsComment> queryWrapper1 = new QueryWrapper<>();
//            queryWrapper1.eq("news_id", news.getNewsId())
//                    .eq("is_deleted", 0)
//                    .orderByDesc("create_time");
//            List<NewsComment> newsComments = newsCommentMapper.selectList(queryWrapper1);
//            for(NewsComment newsComment : newsComments){
//                System.out.println("输出评论 = " + newsComment.getCommentBody());
//            }
//            news.setNewsComments(newsComments);
//        }
//        PageResult pageResult = new PageResult(newsList, newsList.size(), pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }



    @Override
    public PageResult getNewsAndComPage(PageQueryUtil pageUtil) {
        int page = pageUtil.getPage();
        int limit = pageUtil.getLimit();

        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0)
                .orderByDesc("news_id");

        Page<News> newsPage = new Page<>(page, limit);

        Page<News> news = newsMapper.selectPage(newsPage, queryWrapper);

        int total = Math.toIntExact(newsMapper.selectCount(queryWrapper));
        PageResult pageResult = new PageResult(news.getRecords(), total, limit, page);
//        List<News> newsList = newsMapper.findNewsList(pageUtil);
//        int total = newsMapper.getTotalNews(pageUtil);
//        PageResult pageResult = new PageResult(newsList, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }

    @Override
    public List<NewsExcelVO> getData() {
        List<NewsExcelVO> newsExcelVOS = new ArrayList<>();
        List<News> newsList = newsMapper.selectList(null);
        for (int i = 0; i < newsList.size(); i++) {
            News news = newsList.get(i);
            NewsExcelVO newsExcelVO = new NewsExcelVO();
            newsExcelVO.setNewsId(news.getNewsId());
            newsExcelVO.setNewsTitle(news.getNewsTitle());
            newsExcelVO.setNewsContent(news.getNewsContent());
            newsExcelVO.setNewsStatus(news.getNewsStatus());
            newsExcelVO.setNewsViews(news.getNewsViews());
            newsExcelVO.setNewsCategoryId(news.getNewsCategoryId());
            newsExcelVO.setIsDeleted(news.getIsDeleted());
            newsExcelVO.setCreateTime(news.getCreateTime());
            newsExcelVO.setUpdateTime(news.getUpdateTime());
            newsExcelVOS.add(newsExcelVO);
        }
        return newsExcelVOS;
    }

    @Override
    public List<News> queryAll() {
        return newsMapper.selectList(new QueryWrapper<>());
    }


}
